<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { fetchCreateOutboundTask, fetchUpdateOutboundTask, fetchGetOutboundTask } from '@/service/api/outbound';
import { fetchGetOutboundScriptList } from '@/service/api/outbound';
import { $t } from '@/locales';
import { phoneNumberRegExp } from '@/constants/reg';

defineOptions({
  name: 'TaskOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Outbound.Task | null;
  visible: boolean;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增外呼任务',
    edit: '编辑外呼任务'
  };
  return titles[props.operateType];
});

const model: Api.Outbound.TaskOperateParams = reactive(createDefaultModel());

function createDefaultModel(): Api.Outbound.TaskOperateParams {
  return {
    taskId: null,
    taskName: '',
    scriptName: '',
    numberPoolNo: '',
    numberList: '',
    startTime: '',
    endTime: '',
    ringAgainTimes: 0,
    ringAgainInterval: 5,
    forbidTimeList: '',
    concurrency: 1,
    enableDynamicAppend: false,
    inPausedStatus: false,
    isEncryption: false,
    phoneList: []
  };
}

const rules = computed<Record<keyof Api.Outbound.TaskOperateParams, App.Global.FormRule>>(() => {
  // inside computed to make locale reactive, if not apply i18n, you can define it without computed
  const { defaultRequiredRule } = useFormRules();

  return {
    taskId: defaultRequiredRule,
    taskName: defaultRequiredRule,
    scriptName: defaultRequiredRule,
    numberPoolNo: defaultRequiredRule,
    numberList: defaultRequiredRule,
    startTime: defaultRequiredRule,
    endTime: defaultRequiredRule,
    concurrency: [
      { required: true, message: '请输入并发量' },
      { type: 'number', min: 1, max: 100, message: '并发量必须在1-100之间' }
    ],
    ringAgainTimes: [],
    ringAgainInterval: [],
    forbidTimeList: [],
    enableDynamicAppend: [],
    inPausedStatus: [],
    isEncryption: [],
    phoneList: []
  };
});

const scriptOptions = ref<Api.Outbound.Script[]>([]);

async function getScriptOptions() {
  const { data } = await fetchGetOutboundScriptList();
  scriptOptions.value = data || [];
}

/** the enabled script options */
const enabledScriptOptions = computed(() => {
  return scriptOptions.value.filter(script => script.health);
});

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  // 转换数据格式
  const submitData = { ...model };

  // 将numberList字符串转换为数组
  if (typeof submitData.numberList === 'string' && submitData.numberList) {
    try {
      const numberArray = JSON.parse(submitData.numberList);
      if (Array.isArray(numberArray)) {
        submitData.numberList = JSON.stringify(numberArray);
      }
    } catch (error) {
      // 如果不是JSON格式，尝试按逗号分割
      const numbers = submitData.numberList.split(',').map(num => num.trim()).filter(Boolean);
      submitData.numberList = JSON.stringify(numbers);
    }
  }

  // 处理时间格式
  if (submitData.startTime && typeof submitData.startTime === 'number') {
    submitData.startTime = new Date(submitData.startTime).toISOString().slice(0, 19);
  }
  if (submitData.endTime && typeof submitData.endTime === 'number') {
    submitData.endTime = new Date(submitData.endTime).toISOString().slice(0, 19);
  }

  // request
  if (props.operateType === 'add') {
    await fetchCreateOutboundTask(submitData);
    window.$message?.success('新增成功');
  } else if (props.operateType === 'edit') {
    await fetchUpdateOutboundTask(submitData);
    window.$message?.success('更新成功');
  }

  closeDrawer();
  emit('submitted');
}

watch(visible, newValue => {
  if (newValue) {
    handleInitModel();
    restoreValidation();
    getScriptOptions();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="720">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules" size="small" :label-width="100">
        <NGrid :cols="24" :x-gap="18">
          <NFormItemGridItem :span="12" label="任务名称" path="taskName">
            <NInput v-model:value="model.taskName" placeholder="请输入任务名称" />
          </NFormItemGridItem>
          <NFormItemGridItem :span="12" label="剧本名称" path="scriptName">
            <NSelect
              v-model:value="model.scriptName"
              placeholder="请选择剧本"
              :options="enabledScriptOptions.map(item => ({ label: item.name, value: item.script }))"
            />
          </NFormItemGridItem>
          <NFormItemGridItem :span="12" label="号码池编号" path="numberPoolNo">
            <NInput v-model:value="model.numberPoolNo" placeholder="请输入号码池编号" />
          </NFormItemGridItem>
          <NFormItemGridItem :span="12" label="并发量" path="concurrency">
            <NInputNumber v-model:value="model.concurrency" :min="1" :max="100" placeholder="请输入并发量" />
          </NFormItemGridItem>
          <NFormItemGridItem :span="24" label="主叫号码" path="numberList">
            <NInput
              v-model:value="model.numberList"
              type="textarea"
              placeholder="请输入主叫号码列表，JSON格式: [&quot;13812345678&quot;, &quot;13912345678&quot;] 或逗号分隔"
            />
          </NFormItemGridItem>
          <NFormItemGridItem :span="12" label="开始时间" path="startTime">
            <NDatePicker
              v-model:value="model.startTime"
              type="datetime"
              placeholder="请选择开始时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
            />
          </NFormItemGridItem>
          <NFormItemGridItem :span="12" label="结束时间" path="endTime">
            <NDatePicker
              v-model:value="model.endTime"
              type="datetime"
              placeholder="请选择结束时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
            />
          </NFormItemGridItem>
          <NFormItemGridItem :span="12" label="重呼次数" path="ringAgainTimes">
            <NInputNumber v-model:value="model.ringAgainTimes" :min="0" :max="10" placeholder="重呼次数" />
          </NFormItemGridItem>
          <NFormItemGridItem :span="12" label="重呼间隔" path="ringAgainInterval">
            <NInputNumber v-model:value="model.ringAgainInterval" :min="5" :max="1440" placeholder="重呼间隔(分钟)" />
          </NFormItemGridItem>
          <NFormItemGridItem :span="24" label="禁呼时间" path="forbidTimeList">
            <NInput
              v-model:value="model.forbidTimeList"
              type="textarea"
              placeholder="请输入禁呼时间列表，JSON格式: [&quot;W1T16:30:00+08:00/W1T18:20:00+08:00&quot;]"
            />
          </NFormItemGridItem>
          <NFormItemGridItem :span="24">
            <NSpace>
              <NCheckbox v-model:checked="model.enableDynamicAppend">
                启用动态添加号码
              </NCheckbox>
              <NCheckbox v-model:checked="model.inPausedStatus">
                以暂停状态创建
              </NCheckbox>
              <NCheckbox v-model:checked="model.isEncryption">
                加密呼叫
              </NCheckbox>
            </NSpace>
          </NFormItemGridItem>
        </NGrid>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
